"""
基于HTML渲染的PDF转换器
使用无头浏览器将Markdown转换为PDF
"""
import os
import uuid
import tempfile
from datetime import datetime
from typing import Optional
import subprocess
import shutil


class HTMLToPDFConverter:
    def __init__(self):
        self.check_dependencies()
    
    def check_dependencies(self):
        """检查依赖是否可用"""
        # 检查是否有可用的无头浏览器
        self.browser_cmd = None
        
        # 尝试Chrome/Chromium
        chrome_commands = [
            'google-chrome',
            'chromium-browser', 
            'chromium',
            '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
            '/Applications/Chromium.app/Contents/MacOS/Chromium'
        ]
        
        for cmd in chrome_commands:
            if self._check_command(cmd):
                self.browser_cmd = cmd
                break
        
        if not self.browser_cmd:
            raise Exception("未找到Chrome或Chromium浏览器，PDF转换需要无头浏览器支持")
    
    def _check_command(self, cmd):
        """检查命令是否可用"""
        try:
            if cmd.startswith('/Applications/'):
                return os.path.exists(cmd)
            else:
                result = subprocess.run(['which', cmd], capture_output=True)
                return result.returncode == 0
        except:
            return False
    
    def convert_markdown_to_pdf(self, markdown_text: str, title: Optional[str] = None) -> str:
        """
        将Markdown转换为PDF
        
        Args:
            markdown_text: Markdown文本
            title: 文档标题
            
        Returns:
            生成的PDF文件路径
        """
        # 生成HTML内容
        html_content = self._markdown_to_html(markdown_text, title)
        
        # 生成临时HTML文件
        temp_html = None
        output_pdf = None
        
        try:
            # 创建临时HTML文件
            with tempfile.NamedTemporaryFile(mode='w', suffix='.html', 
                                           delete=False, encoding='utf-8') as f:
                f.write(html_content)
                temp_html = f.name
            
            # 生成输出PDF路径
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"html_pdf_export_{timestamp}_{uuid.uuid4().hex[:8]}.pdf"
            
            # 确保temp目录存在
            os.makedirs("temp", exist_ok=True)
            output_pdf = os.path.join("temp", filename)
            
            # 使用Chrome无头模式转换为PDF
            chrome_cmd = [
                self.browser_cmd,
                '--headless',
                '--disable-gpu',
                '--no-sandbox',
                '--disable-dev-shm-usage',
                '--print-to-pdf=' + output_pdf,
                '--print-to-pdf-no-header',
                '--run-all-compositor-stages-before-draw',
                '--virtual-time-budget=5000',
                f'file://{os.path.abspath(temp_html)}'
            ]
            
            # 执行转换
            result = subprocess.run(chrome_cmd, capture_output=True, text=True, timeout=30)
            
            if result.returncode != 0:
                error_msg = result.stderr or "PDF转换失败"
                raise Exception(f"Chrome PDF转换错误: {error_msg}")
            
            # 检查输出文件是否生成
            if not os.path.exists(output_pdf):
                raise Exception("PDF转换完成但未找到输出文件")
            
            return output_pdf
            
        except subprocess.TimeoutExpired:
            raise Exception("PDF转换超时")
        except Exception as e:
            # 清理可能生成的文件
            if output_pdf and os.path.exists(output_pdf):
                try:
                    os.remove(output_pdf)
                except:
                    pass
            raise e
        finally:
            # 清理临时HTML文件
            if temp_html and os.path.exists(temp_html):
                try:
                    os.remove(temp_html)
                except:
                    pass
    
    def _markdown_to_html(self, markdown_text: str, title: Optional[str] = None) -> str:
        """
        将Markdown转换为HTML
        """
        # 简单的Markdown到HTML转换
        html_content = markdown_text
        
        # 尝试使用marked.js进行转换（如果可用）
        try:
            import markdown
            html_body = markdown.markdown(
                html_content,
                extensions=['tables', 'fenced_code', 'codehilite']
            )
        except ImportError:
            # 如果没有markdown库，使用简单的转换
            html_body = self._simple_markdown_to_html(html_content)
        
        # 生成完整的HTML文档
        page_title = title or "AI对话导出"
        
        html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{page_title}</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: white;
        }}
        
        h1, h2, h3, h4, h5, h6 {{
            color: #2c3e50;
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }}
        
        h1 {{ font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: 10px; }}
        h2 {{ font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: 8px; }}
        h3 {{ font-size: 1.25em; }}
        
        p {{ margin-bottom: 16px; }}
        
        strong {{ font-weight: 600; }}
        em {{ font-style: italic; }}
        
        code {{
            background: #f6f8fa;
            border-radius: 3px;
            font-size: 85%;
            margin: 0;
            padding: 0.2em 0.4em;
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
        }}
        
        pre {{
            background: #f6f8fa;
            border-radius: 6px;
            font-size: 85%;
            line-height: 1.45;
            overflow: auto;
            padding: 16px;
            margin-bottom: 16px;
        }}
        
        pre code {{
            background: transparent;
            border: 0;
            display: inline;
            line-height: inherit;
            margin: 0;
            max-width: auto;
            overflow: visible;
            padding: 0;
            word-wrap: normal;
        }}
        
        ul, ol {{
            margin-bottom: 16px;
            padding-left: 2em;
        }}
        
        li {{ margin-bottom: 4px; }}
        
        blockquote {{
            border-left: 4px solid #dfe2e5;
            color: #6a737d;
            margin: 0 0 16px 0;
            padding: 0 16px;
        }}
        
        table {{
            border-collapse: collapse;
            border-spacing: 0;
            width: 100%;
            margin-bottom: 16px;
        }}
        
        table th, table td {{
            border: 1px solid #dfe2e5;
            padding: 6px 13px;
        }}
        
        table th {{
            background-color: #f6f8fa;
            font-weight: 600;
        }}
        
        table tr:nth-child(2n) {{
            background-color: #f6f8fa;
        }}
        
        hr {{
            border: 0;
            border-top: 1px solid #eaecef;
            height: 0;
            margin: 24px 0;
        }}
        
        @media print {{
            body {{ margin: 0; padding: 15px; }}
            h1, h2, h3, h4, h5, h6 {{ page-break-after: avoid; }}
            pre, blockquote {{ page-break-inside: avoid; }}
            table {{ page-break-inside: avoid; }}
        }}
    </style>
</head>
<body>
    {html_body}
</body>
</html>"""
        
        return html_template
    
    def _simple_markdown_to_html(self, markdown_text: str) -> str:
        """
        简单的Markdown到HTML转换（备用方案）
        """
        html = markdown_text
        
        # 标题
        html = html.replace('\n# ', '\n<h1>').replace('\n## ', '\n<h2>').replace('\n### ', '\n<h3>')
        html = html.replace('\n#### ', '\n<h4>').replace('\n##### ', '\n<h5>').replace('\n###### ', '\n<h6>')
        
        # 粗体和斜体
        import re
        html = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', html)
        html = re.sub(r'\*(.*?)\*', r'<em>\1</em>', html)
        
        # 行内代码
        html = re.sub(r'`(.*?)`', r'<code>\1</code>', html)
        
        # 代码块
        html = re.sub(r'```(.*?)```', r'<pre><code>\1</code></pre>', html, flags=re.DOTALL)
        
        # 列表（简单处理）
        lines = html.split('\n')
        in_list = False
        result_lines = []
        
        for line in lines:
            if line.strip().startswith('- '):
                if not in_list:
                    result_lines.append('<ul>')
                    in_list = True
                result_lines.append(f'<li>{line.strip()[2:]}</li>')
            else:
                if in_list:
                    result_lines.append('</ul>')
                    in_list = False
                if line.strip():
                    result_lines.append(f'<p>{line}</p>')
                else:
                    result_lines.append('<br>')
        
        if in_list:
            result_lines.append('</ul>')
        
        return '\n'.join(result_lines)


def convert_markdown_to_pdf_html(markdown_text: str, title: Optional[str] = None) -> str:
    """
    便捷函数：使用HTML渲染方式将Markdown转换为PDF
    
    Args:
        markdown_text: Markdown文本
        title: 文档标题
        
    Returns:
        生成的PDF文件路径
    """
    converter = HTMLToPDFConverter()
    return converter.convert_markdown_to_pdf(markdown_text, title)


def is_html_pdf_available() -> bool:
    """检查HTML转PDF功能是否可用"""
    try:
        converter = HTMLToPDFConverter()
        return True
    except:
        return False